#coding=utf-8
from  socket import *

class Scanport():
    
    def __init__(self, timeout=1):
        #self.www=www
        #self.port=port
        self.timeout=timeout
        self.open_port=[]

    def run(self,www,port=[80,8080,8888]):
        self.port=port
        self.www=www
        #ip 失败
        if not self.get_host():   
            return   {self.www:False} 
        for self.p in self.port:
            if  self.scan_port(self.p):
                self.open_port.append(self.p)
        if len(self.open_port)==0:return {self.www:{self.host:None}}
        else:
            return  {self.www:{self.host:self.open_port}} 
    
    def scan_port(self, port):
        
        try:
           
            con=socket(AF_INET, SOCK_STREAM)
            con.settimeout(self.timeout)
            con.connect((self.host, port))
            con.settimeout(None)
            con.close()
            #端口打开
            return port
        except Exception,e:
            #端口关闭
            return False

    def get_host(self):
        try:
            self.host=gethostbyname(self.www)
            return True
        except:
            self.host=self.www
            return False


if __name__=='__main__':
    S=Scanport()
    print S.run('blog.001jm.com',[27017,321,123])
